package com.code.services.impl;

import com.code.daos.robot.BanGroupUrlMapper;
import com.code.enums.ResultCode;
import com.code.exceptions.BusinessException;
import com.code.models.robot.BanGroupUrl;
import com.code.services.BanGroupUrlService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 禁止完成群分享任务的群地址服务实现类
 *
 * @author xiaoyaowang
 */
@Service
public class BanGroupUrlServiceImpl implements BanGroupUrlService {

    @Resource
    BanGroupUrlMapper banGroupUrlMapper;

    @Override
    public PageInfo<BanGroupUrl> getBanGroupUrlListByCondition(String groupUrl, Integer page, Integer pageSize) {
        PageHelper.startPage(page, pageSize);
        List<BanGroupUrl> list = banGroupUrlMapper.getBanGroupUrlListByCondition(groupUrl);
        return PageInfo.of(list);
    }

    @Override
    public void deleteBanGroupUrlById(Integer id) {
        BanGroupUrl banGroupUrl = banGroupUrlMapper.selectByPrimaryKey(id);
        if (null != banGroupUrl) {
            banGroupUrlMapper.deleteByPrimaryKey(id);
        }
    }

    @Override
    public int addBanGroupUrl(BanGroupUrl banGroupUrl) {
        String groupUrl = banGroupUrl.getGroupUrl();
        if (StringUtils.isBlank(groupUrl)) {
            throw new BusinessException(ResultCode.GROUP_URL_CANNOT_NULL);
        }
        Integer banGroupUrlPresent = banGroupUrlMapper.banGroupUrlPresent(groupUrl);
        if (null != banGroupUrlPresent) {
            throw new BusinessException(ResultCode.GROUP_URL_CANNOT_SAME_ERROR);
        }
        if (StringUtils.isNotBlank(groupUrl)) {
            banGroupUrl.setDeleted(0);
            banGroupUrl.setCreatedAt(new Date());
            banGroupUrl.setUpdatedAt(new Date());
            return banGroupUrlMapper.insert(banGroupUrl);
        }
        return 0;
    }

    @Override
    public int updateBanGroupUrl(BanGroupUrl banGroupUrl) {
        String groupUrl = banGroupUrl.getGroupUrl();
        if (StringUtils.isBlank(groupUrl)) {
            throw new BusinessException(ResultCode.GROUP_URL_CANNOT_NULL);
        }
        Integer banGroupUrlPresent = banGroupUrlMapper.banGroupUrlPresent(groupUrl);
        if (null != banGroupUrlPresent) {
            throw new BusinessException(ResultCode.GROUP_URL_CANNOT_SAME_ERROR);
        }
        if (StringUtils.isNotBlank(groupUrl)) {
            if (null != banGroupUrlMapper.selectByPrimaryKey(banGroupUrl.getId())) {
                banGroupUrl.setUpdatedAt(new Date());
                return banGroupUrlMapper.updateByPrimaryKeySelective(banGroupUrl);
            }
        }
        return 0;
    }
}
